<template>
  <div class="html-component" :id="id">
    <cmp :html="html" :id="id"></cmp>
    <div style="display: none" id="dom-hidden-div"></div>
  </div>
</template>

<script>
import Vue from 'vue';
export default {
  name: 'MyHtmlComponent',
  props: {
    html: String,
    id: {
      default: 'id111',
      type: String
    }
  },
  data() {
    return {
      style: null
    };
  },
  components: {
    cmp: {
      name: 'CustomComponent',
      props: {
        html: String,
        id: String
      },
      methods: {
        getSource(type) {
          const reg = new RegExp(`<${type}[^>]*>`);
          // $('#dom-hidden-div').html()
          let content = this.html;
          let matches = content.match(reg);
          if (matches) {
            let start = content.indexOf(matches[0]) + matches[0].length;
            let end = content.lastIndexOf(`</${type}`);
            return content.slice(start, end);
          }
        }
      },
      render(h) {
        let obj = {};
        let template = this.getSource('template');
        if (!template) {
          this.$message.error('缺少template标签');
          // return '小伙子，请认真检查代码格式~';
          obj.template =
            '<div style="color:red">小伙子，请认真检查代码格式~</div>';
        } else {
          let script = this.getSource('script');
          if (script) {
            try {
              script = script.replace(/export default/, 'return');
              obj = new Function(script)();
              obj.template = '<div>' + template + '</div>';
            } catch (error) {
              this.$message.error('script格式可能不正确');
              obj.template =
                '<div style="color:red">小伙子，请认真检查代码格式~</div>';
            }
          } else {
            obj.template = '<div>' + template + '</div>';
          }
        }
        this.style = this.getSource('style');

        this.$nextTick(() => {
          $('#' + this.id)
            .find('style')
            .remove();
          if (this.style) {
            $('#' + this.id).prepend('<style>' + this.style + '</style>');
          }
        });
        const com = Vue.extend(obj);
        return h(com, {});
      }
    }
  },

  mounted() {}
};
</script>
<style lang="scss" scoped>
.html-component {
  width: 100%;
}
</style>